package com.easonji.core.aop;

import java.lang.reflect.Method;
import java.util.List;
import java.util.regex.Pattern;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.easonji.common.cache.util.CacheUtils;
import com.easonji.core.annotion.CacheRemove;

/**
 * @ClassName: CacheRemoveAop
 * @Description: 缓存批量删除AOP
 * @Author: LiuJun
 * @date: 2018/07/18 17:18
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Aspect
@Component
public class CacheRemoveAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.easonji.core.annotion.CacheRemove)")
    private void cutCacheRemove() {
    }

    @Around("cutCacheRemove()")
    public Object doCacheRemove(ProceedingJoinPoint point) throws Throwable {
        // 先执行业务
        Object result = point.proceed();
        try {
            handle(point);
        } catch (Exception e) {
            log.error("缓存删除出错!", e);
        }
        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
        if (cacheRemove != null) {
            String value = cacheRemove.value();
            // 需要移除的正则key
            String[] keys = cacheRemove.key();
            List<Object> cacheKeys = CacheUtils.getKeys(value);
            for (String key : keys) {
                Pattern pattern = Pattern.compile(key);
                for (Object cacheKey : cacheKeys) {
                    String cacheKeyStr = String.valueOf(cacheKey);
                    if (pattern.matcher(cacheKeyStr).find()) {
                        CacheUtils.remove(value, cacheKeyStr);
                    }
                }
            }
        }
    }
}
